<script setup lang="ts">
import { ref, onMounted, onUnmounted, reactive } from 'vue';

const el = ref(null)
    const { width, height } = useElementSize(el)

    return {
      el,
      width,
      height,
    }
const useElementSize = (targetRef) => {
  const width = ref(0);
  const height = ref(0);

  const updateSize = () => {
    if (targetRef.value) {
        // 内部的宽度，内部的高度
      const { clientWidth, clientHeight } = targetRef.value;
      width.value = clientWidth;
      height.value = clientHeight;
    }
  };

  onMounted(() => {
    updateSize();
    // 浏览器窗口大小发生变化时触发，利用resize该事件跟踪窗口大小的变化来动态调整页面的元素显示
    window.addEventListener('resize', updateSize);
  });

  onUnmounted(() => {
    window.removeEventListener('resize', updateSize);
  });

  return {
    width,
    height,
  };
};


export default useElementSize;
</script>

<template>
    <div ref="el">
      Height: {{ height }}
      Width: {{ width }}
    </div>
  </template>